<template>
  <div class="resource-capability-tab">
    <div class="tab-content">
      <div class="section-header">
        <h3>资源能力</h3>
        <div class="header-actions">
          <Button @click="showCapabilityGuide">
            <IconifyIcon icon="ant-design:question-circle-outlined" />
            使用指南
          </Button>
          <Button @click="showImportExport">
            <IconifyIcon icon="ant-design:import-outlined" />
            导入/导出
          </Button>
          <Button @click="showBatchOperations">
            <IconifyIcon icon="ant-design:setting-outlined" />
            批量操作
          </Button>
          <Button type="primary" @click="editCapabilities">
            <IconifyIcon icon="ant-design:plus-outlined" />
            添加能力
          </Button>
        </div>
      </div>

      <!-- 能力展示网格 -->
      <div class="capabilities-grid">
        <div
          v-for="capability in parsedCapabilities"
          :key="capability.key"
          class="capability-item"
        >
          <div class="capability-header">
            <IconifyIcon
              :icon="capability.icon"
              :style="{ color: capability.color }"
            />
            <div class="capability-info">
              <div class="capability-name">{{ capability.label }}</div>
              <div class="capability-desc">
                {{ capability.description }}
              </div>
              <div class="capability-meta">
                <Tag size="small" :color="getTypeColor(capability.type)">
                  {{ getTypeLabel(capability.type) }}
                </Tag>
                <Tag :color="capability.enabled ? 'green' : 'red'" size="small">
                  {{ capability.enabled ? '启用' : '禁用' }}
                </Tag>
              </div>
            </div>
            <div class="capability-actions">
              <Button
                type="link"
                size="small"
                @click="toggleCapability(capability.key)"
              >
                <IconifyIcon
                  :icon="
                    capability.enabled
                      ? 'ant-design:stop-outlined'
                      : 'ant-design:play-circle-outlined'
                  "
                />
                {{ capability.enabled ? '禁用' : '启用' }}
              </Button>
              <Button
                type="link"
                size="small"
                @click="editCapability(capability.key)"
              >
                <IconifyIcon icon="ant-design:edit-outlined" />
                配置
              </Button>
              <Button
                type="link"
                size="small"
                @click="copyCapability(capability.key)"
              >
                <IconifyIcon icon="ant-design:copy-outlined" />
                复制
              </Button>
              <Button
                type="link"
                size="small"
                @click="exportCapability(capability.key)"
              >
                <IconifyIcon icon="ant-design:export-outlined" />
                导出
              </Button>
              <Button
                type="link"
                size="small"
                danger
                @click="removeCapability(capability.key)"
              >
                <IconifyIcon icon="ant-design:delete-outlined" />
                删除
              </Button>
            </div>
          </div>
        </div>
      </div>

      <!-- 能力为空时的提示 -->
      <div v-if="!hasCapabilities" class="empty-state">
        <IconifyIcon
          icon="ant-design:thunderbolt-outlined"
          class="empty-icon"
        />
        <p>暂无能力配置</p>
        <Button type="primary" @click="editCapabilities">
          <IconifyIcon icon="ant-design:plus-outlined" />
          添加能力
        </Button>
      </div>
    </div>

    <!-- 能力配置模态框 -->
    <CapabilityConfigModal
      :visible="capabilityConfigVisible"
      :capability="currentEditingCapability"
      :resource="resource"
      @update:visible="capabilityConfigVisible = $event"
      @save="onCapabilityConfigSave"
    />

    <!-- 能力模板库模态框 -->
    <!-- <Modal
      v-model:visible="capabilityTemplateVisible"
      title="能力模板库"
      width="90%"
      :footer="null"
      :destroyOnClose="true"
    >
      <CapabilityTemplateLibrary
        v-if="capabilityTemplateVisible"
        @select="onTemplateSelect"
        @close="capabilityTemplateVisible = false"
      />
    </Modal> -->

    <!-- 能力管理指南 -->
    <!-- <ResourceCapabilityGuide
      :visible="capabilityGuideVisible"
      @update:visible="(val) => (capabilityGuideVisible = val)"
    /> -->

    <!-- 导入/导出模态框 -->
    <Modal
      v-model:visible="importExportVisible"
      title="能力导入/导出"
      width="600px"
      :footer="null"
      :destroy-on-close="true"
    >
      <div class="import-export-modal">
        <div class="import-section">
          <h4>导入能力</h4>
          <p>选择JSON文件导入能力配置</p>
          <Button @click="handleImport" type="primary">
            <IconifyIcon icon="ant-design:upload-outlined" />
            选择文件
          </Button>
          <input
            ref="fileInput"
            type="file"
            accept=".json"
            style="display: none"
            @change="onFileSelected"
          />
        </div>

        <div class="export-section">
          <h4>导出能力</h4>
          <p>导出所有能力配置为JSON文件</p>
          <Button @click="handleExportAll" type="primary">
            <IconifyIcon icon="ant-design:download-outlined" />
            导出全部
          </Button>
        </div>
      </div>
    </Modal>

    <!-- 批量操作模态框 -->
    <Modal
      v-model:visible="batchOperationsVisible"
      title="批量操作"
      width="600px"
      :footer="null"
      :destroy-on-close="true"
    >
      <div class="batch-operations-modal">
        <div class="selection-section">
          <h4>选择能力</h4>
          <p>选择要批量操作的能力</p>
          <div class="capability-checkboxes">
            <div
              v-for="capability in parsedCapabilities"
              :key="capability.key"
              class="checkbox-item"
            >
              <input
                type="checkbox"
                :id="capability.key"
                :value="capability.key"
                v-model="selectedCapabilities"
              />
              <label :for="capability.key">{{ capability.label }}</label>
            </div>
          </div>
        </div>

        <div class="operations-section">
          <h4>批量操作</h4>
          <div class="operation-buttons">
            <Button @click="batchEnable" type="primary">
              <IconifyIcon icon="ant-design:play-circle-outlined" />
              批量启用
            </Button>
            <Button @click="batchDisable" type="default">
              <IconifyIcon icon="ant-design:stop-outlined" />
              批量禁用
            </Button>
            <Button @click="batchDelete" danger>
              <IconifyIcon icon="ant-design:delete-outlined" />
              批量删除
            </Button>
            <Button @click="batchExport" type="primary">
              <IconifyIcon icon="ant-design:export-outlined" />
              批量导出
            </Button>
          </div>
        </div>
      </div>
    </Modal>
  </div>
</template>

<script lang="ts" setup>
import { computed, ref } from 'vue';

import { Button, message, Modal, Tag } from 'ant-design-vue';

import { IconifyIcon } from '@vben/icons';

import CapabilityConfigModal from '../../capability/components/CapabilityConfigModal.vue';

interface Resource {
  id?: number | string;
  name?: string;
  capabilities?: string;
  [key: string]: any;
}

// interface _Capability {
//   key: string;keykey
//   label: string;labellabel
//   description: string;descriptiondescription
//   type: string;typetype
//   enabled: boolean;enabledenabled
//   icon: string;iconicon
//   color: string;colorcolor
//   [key: string]: any;keykey
// }

const props = defineProps<{
  resource?: Resource;
}>();

const emit = defineEmits<{
  capabilityUpdate: [capabilities: any];
  editCapability: [capabilityKey: string];
}>();

// 能力管理相关状态
const capabilityConfigVisible = ref(false);
const currentEditingCapability = ref<any>(null);

// 导入/导出相关状态
const importExportVisible = ref(false);
const selectedCapabilities = ref<string[]>([]);

// 批量操作相关状态
const batchOperationsVisible = ref(false);

// 解析能力数据
const parsedCapabilities = computed(() => {
  if (!props.resource?.capabilities) return [];
  try {
    const capabilities = JSON.parse(props.resource.capabilities);
    if (Array.isArray(capabilities)) {
      return capabilities.map((capability: any) => ({
        key: capability.id || capability.key,
        label: getCapabilityName(capability),
        description: getCapabilityDescription(capability),
        type: capability.implementation?.type || 'api',
        enabled: capability.enabled || false,
        icon: getCapabilityIcon(capability),
        color: getCapabilityColor(capability),
        ...capability,
      }));
    } else if (typeof capabilities === 'object') {
      return Object.keys(capabilities).map((key) => {
        const capability = capabilities[key];
        return {
          key,
          label: getCapabilityName(capability),
          description: getCapabilityDescription(capability),
          type: capability.implementation?.type || 'api',
          enabled: capability.enabled || false,
          icon: getCapabilityIcon(capability),
          color: getCapabilityColor(capability),
          ...capability,
        };
      });
    }
    return [];
  } catch (error) {
    console.error('解析能力数据失败:', error);
    return [];
  }
});

// 是否有能力数据
const hasCapabilities = computed(() => {
  return parsedCapabilities.value.length > 0;
});

// 能力管理方法
const showCapabilityGuide = () => {
  // capabilityGuideVisible.value = true;
  message.info('能力管理指南功能待完善');
};

const editCapabilities = () => {
  // capabilityTemplateVisible.value = true;
  message.info('添加能力功能待完善');
};

const showImportExport = () => {
  importExportVisible.value = true;
  message.info('导入/导出功能待完善');
};

const showBatchOperations = () => {
  batchOperationsVisible.value = true;
  selectedCapabilities.value = [];
};

const toggleCapability = (capabilityKey: string) => {
  const capability = parsedCapabilities.value.find(
    (cap) => cap.key === capabilityKey,
  );
  if (capability) {
    const updatedCapabilities = parsedCapabilities.value.map((cap) => {
      if (cap.key === capabilityKey) {
        return { ...cap, enabled: !cap.enabled };
      }
      return cap;
    });
    emit('capabilityUpdate', updatedCapabilities);
    message.success(
      `${capability.enabled ? '禁用' : '启用'}能力: ${capability.label}`,
    );
  }
};

const editCapability = (capabilityKey: string) => {
  const capability = parsedCapabilities.value.find(
    (cap) => cap.key === capabilityKey,
  );
  if (capability) {
    currentEditingCapability.value = capability;
    capabilityConfigVisible.value = true;
  }
};

const removeCapability = (capabilityKey: string) => {
  const capability = parsedCapabilities.value.find(
    (cap) => cap.key === capabilityKey,
  );
  if (capability) {
    const updatedCapabilities = parsedCapabilities.value.filter(
      (cap) => cap.key !== capabilityKey,
    );
    emit('capabilityUpdate', updatedCapabilities);
    message.success(`删除能力: ${capability.label}`);
  }
};

const copyCapability = (capabilityKey: string) => {
  const capability = parsedCapabilities.value.find(
    (cap) => cap.key === capabilityKey,
  );
  if (capability) {
    const copiedCapability = {
      ...capability,
      key: `${capability.key}_copy_${Date.now()}`,
      label: `${capability.label} (副本)`,
      enabled: false,
      enabledenabled,
    };
    const updatedCapabilities = [...parsedCapabilities.value, copiedCapability];
    emit('capabilityUpdate', updatedCapabilities);
    message.success(`复制能力: ${capability.label}`);
  }
};

const exportCapability = (capabilityKey: string) => {
  const capability = parsedCapabilities.value.find(
    (cap) => cap.key === capabilityKey,
  );
  if (capability) {
    const exportData = {
      capability,
      exportTime: new Date().toISOString(),
      version: '1.0.0',
    };

    // 创建下载链接
    const dataStr = JSON.stringify(exportData, null, 2);
    const dataBlob = new Blob([dataStr], { type: 'application/json' });
    const url = URL.createObjectURL(dataBlob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `${capability.label}_${Date.now()}.json`;
    link.click();
    URL.revokeObjectURL(url);

    message.success(`导出能力: ${capability.label}`);
  }
};

// 导入/导出相关方法
const fileInput = ref<HTMLInputElement>();

const handleImport = () => {
  fileInput.value?.click();
};

const onFileSelected = (event: Event) => {
  const target = event.target as HTMLInputElement;
  const file = target.files?.[0];
  if (file) {
    const reader = new FileReader();
    reader.addEventListener('load', (e) => {
      try {
        const content = e.target?.result as string;
        const importData = JSON.parse(content);

        if (importData.capability) {
          const importedCapability = {
            ...importData.capability,
            key: `${importData.capability.key}_imported_${Date.now()}`,
            label: `${importData.capability.label} (导入)`,
            enabled: false,
          };

          const updatedCapabilities = [
            ...parsedCapabilities.value,
            importedCapability,
          ];
          emit('capabilityUpdate', updatedCapabilities);
          message.success(`导入能力: ${importData.capability.label}`);
        } else {
          message.error('文件格式不正确');
        }
      } catch {
        message.error('解析文件失败');
      }
    });
    reader.readAsText(file);
  }
};

const handleExportAll = () => {
  const exportData = {
    capabilities: parsedCapabilities.value,
    exportTime: new Date().toISOString(),
    version: '1.0.0',
    resourceName: props.resource?.name || 'unknown',
  };

  const dataStr = JSON.stringify(exportData, null, 2);
  const dataBlob = new Blob([dataStr], { type: 'application/json' });
  const url = URL.createObjectURL(dataBlob);
  const link = document.createElement('a');
  link.href = url;
  link.download = `capabilities_${props.resource?.name || 'resource'}_${Date.now()}.json`;
  link.click();
  URL.revokeObjectURL(url);

  message.success('导出所有能力配置成功');
};

// 批量操作相关方法
const batchEnable = () => {
  if (selectedCapabilities.value.length === 0) {
    message.warning('请先选择要操作的能力');
    return;
  }

  const updatedCapabilities = parsedCapabilities.value.map((capability) => {
    if (selectedCapabilities.value.includes(capability.key)) {
      return { ...capability, enabled: true };
    }
    return capability;
  });

  emit('capabilityUpdate', updatedCapabilities);
  message.success(`已启用 ${selectedCapabilities.value.length} 个能力`);
  batchOperationsVisible.value = false;
};

const batchDisable = () => {
  if (selectedCapabilities.value.length === 0) {
    message.warning('请先选择要操作的能力');
    return;
  }

  const updatedCapabilities = parsedCapabilities.value.map((capability) => {
    if (selectedCapabilities.value.includes(capability.key)) {
      return { ...capability, enabled: false };
    }
    return capability;
  });

  emit('capabilityUpdate', updatedCapabilities);
  message.success(`已禁用 ${selectedCapabilities.value.length} 个能力`);
  batchOperationsVisible.value = false;
};

const batchDelete = () => {
  if (selectedCapabilities.value.length === 0) {
    message.warning('请先选择要操作的能力');
    return;
  }

  const updatedCapabilities = parsedCapabilities.value.filter(
    (capability) => !selectedCapabilities.value.includes(capability.key),
  );

  emit('capabilityUpdate', updatedCapabilities);
  message.success(`已删除 ${selectedCapabilities.value.length} 个能力`);
  batchOperationsVisible.value = false;
};

const batchExport = () => {
  if (selectedCapabilities.value.length === 0) {
    message.warning('请先选择要操作的能力');
    return;
  }

  const selectedCapabilitiesData = parsedCapabilities.value.filter(
    (capability) => selectedCapabilities.value.includes(capability.key),
  );

  const exportData = {
    capabilities: selectedCapabilitiesData,
    exportTime: new Date().toISOString(),
    version: '1.0.0',
    resourceName: props.resource?.name || 'unknown',
  };

  const dataStr = JSON.stringify(exportData, null, 2);
  const dataBlob = new Blob([dataStr], { type: 'application/json' });
  const url = URL.createObjectURL(dataBlob);
  const link = document.createElement('a');
  link.href = url;
  link.download = `selected_capabilities_${props.resource?.name || 'resource'}_${Date.now()}.json`;
  link.click();
  URL.revokeObjectURL(url);

  message.success(`已导出 ${selectedCapabilities.value.length} 个能力配置`);
  batchOperationsVisible.value = false;
};

// 能力配置保存处理
const onCapabilityConfigSave = (capability: any) => {
  // 更新能力列表中的对应项
  const updatedCapabilities = parsedCapabilities.value.map((cap) => {
    if (cap.key === capability.key) {
      return {
        ...cap,
        ...capability,
        label: getCapabilityName(capability),
        description: getCapabilityDescription(capability),
        icon: getCapabilityIcon(capability),
        color: getCapabilityColor(capability),
      };
    }
    return cap;
  });

  emit('capabilityUpdate', updatedCapabilities);
  message.success('能力配置已保存');
  capabilityConfigVisible.value = false;
};

// 辅助方法
const getCapabilityName = (capability: any) => {
  return capability.name || capability.label || capability.key || '未知能力';
};

const getCapabilityDescription = (capability: any) => {
  return capability.description || capability.desc || '暂无描述';
};

const getCapabilityIcon = (capability: any) => {
  return capability.icon || 'ant-design:thunderbolt-outlined';
};

const getCapabilityColor = (capability: any) => {
  return capability.color || '#1890ff';
};

const getTypeColor = (type: string) => {
  switch (type) {
    case 'api': {
      return 'blue';
    }
    case 'function': {
      return 'green';
    }
    case 'integration': {
      return 'orange';
    }
    case 'service': {
      return 'purple';
    }
    default: {
      return 'default';
    }
  }
};

const getTypeLabel = (type: string) => {
  switch (type) {
    case 'api': {
      return 'API';
    }
    case 'function': {
      return '函数';
    }
    case 'integration': {
      return '集成';
    }
    case 'service': {
      return '服务';
    }
    default: {
      return type;
    }
  }
};
</script>

<style scoped>
/* 响应式设计 */
@media (max-width: 768px) {
  .section-header {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
  }

  .header-actions {
    justify-content: flex-start;
    width: 100%;
  }

  .capabilities-grid {
    grid-template-columns: 1fr;
  }

  .capability-header {
    flex-direction: column;
    align-items: flex-start;
  }

  .capability-actions {
    flex-direction: row;
    justify-content: flex-end;
    width: 100%;
  }
}

.resource-capability-tab {
  padding: 16px;
}

.tab-content {
  min-height: 400px;
}

.section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-bottom: 16px;
  margin-bottom: 24px;
  border-bottom: 1px solid #f0f0f0;
}

.section-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #262626;
}

.header-actions {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.capabilities-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
  gap: 16px;
  margin-top: 16px;
}

.capability-item {
  padding: 16px;
  background: #fafafa;
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.capability-item:hover {
  background: #f5f5f5;
  border-color: #d9d9d9;
  box-shadow: 0 2px 8px rgb(0 0 0 / 10%);
}

.capability-header {
  display: flex;
  gap: 12px;
  align-items: flex-start;
}

.capability-header > :first-child {
  margin-top: 4px;
  font-size: 24px;
}

.capability-info {
  flex: 1;
  min-width: 0;
}

.capability-name {
  margin-bottom: 4px;
  font-size: 14px;
  font-weight: 600;
  color: #262626;
}

.capability-desc {
  margin-bottom: 8px;
  font-size: 12px;
  line-height: 1.4;
  color: #595959;
}

.capability-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.capability-actions {
  display: flex;
  flex-direction: column;
  gap: 4px;
  align-items: flex-end;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  color: #8c8c8c;
  text-align: center;
}

.empty-icon {
  margin-bottom: 16px;
  font-size: 48px;
  color: #d9d9d9;
}

.empty-state p {
  margin: 0 0 16px;
  font-size: 16px;
}

.import-export-modal {
  padding: 16px;
}

.import-export-modal .import-section,
.import-export-modal .export-section {
  padding: 16px;
  margin-bottom: 24px;
  background: #fafafa;
  border: 1px solid #f0f0f0;
  border-radius: 8px;
}

.import-export-modal .import-section h4,
.import-export-modal .export-section h4 {
  margin: 0 0 8px;
  font-size: 16px;
  font-weight: 600;
  color: #262626;
}

.import-export-modal .import-section p,
.import-export-modal .export-section p {
  margin: 0 0 16px;
  font-size: 14px;
  color: #595959;
}

.import-export-modal .import-section {
  background: #f0f8ff;
  border-color: #1890ff;
}

.import-export-modal .export-section {
  background: #f6ffed;
  border-color: #52c41a;
}

.batch-operations-modal {
  padding: 16px;
}

.batch-operations-modal .selection-section,
.batch-operations-modal .operations-section {
  padding: 16px;
  margin-bottom: 24px;
  background: #fafafa;
  border: 1px solid #f0f0f0;
  border-radius: 8px;
}

.batch-operations-modal .selection-section h4,
.batch-operations-modal .operations-section h4 {
  margin: 0 0 8px;
  font-size: 16px;
  font-weight: 600;
  color: #262626;
}

.batch-operations-modal .selection-section p {
  margin: 0 0 16px;
  font-size: 14px;
  color: #595959;
}

.capability-checkboxes {
  max-height: 200px;
  padding: 8px;
  overflow-y: auto;
  background: #fff;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
}

.checkbox-item {
  display: flex;
  align-items: center;
  padding: 4px 0;
}

.checkbox-item input[type='checkbox'] {
  margin-right: 8px;
}

.checkbox-item label {
  font-size: 14px;
  color: #262626;
  cursor: pointer;
}

.operation-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}
</style>
